<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\service\orderService;
use app\service\invoiceService;
use think\Db;
use think\Controller;
use invoice\Api;
use think\db\Where;

class Invoice extends Controller{
    //商户授权
    public function auth(){
        $code=request()->get("code");
        $taxnum=request()->get("taxnum");
        $appKey="uXig5unv";
        $appSecret="B69D206D6E564A6E";
        $proinvoice=(new invoiceService())->invoiceInfo($taxnum);
        if(empty($proinvoice)){
            return "<div style='color:red;font-size:50px;margin-top:50px;text-align:center'>该商户不存在</div>";
        }
        $redirectUri="https://www.aliwgzf.com/admin/invoice/auth";
        $res = Api::getISVToken($appKey, $appSecret, $code, $taxnum, $redirectUri);
        
        $res=json_decode($res,true);
        if(array_key_exists("error",$res)){
            return $res["error_description"];
        }else{
            $info["fp_expires_in"]=date("Y-m-d H:i:s");
            $info["fp_access_token"]=$res["access_token"];
            $info["fp_refresh_token"]=$res["refresh_token"];
            $info["userId"]=$res["userId"];
            $re=Db::table("service_invoice")->where("service_id",$proinvoice["service_id"])->update($info);
            if($re){
                return "<div style='color:green;font-size:50px;margin-top:50px;text-align:center'>授权成功</div>";
            }else{
                return "<div style='color:red;font-size:50px;margin-top:50px;text-align:center'>授权失败，请重新授权</div>";
            }
        }
        
    }
    public function test(){
        $str=$this->refreshISVToken();
        var_dump($str);
    }
    public function es(){
        $str='{"access_token":"688b2c72f110863804f4081ceqoynvbi","refresh_token":"c74cad8454d6e44daa3117ebdb6ce1c0","expires_in":86400}';
    }
    
    public function refreshISVToken() {
		$refreshToken = "27630227357ca8f7705ed88482a06f3a";
		$appSecret = "B69D206D6E564A6E";
		$userId = "c639b2dba1ca4d4cb740d7db8e9da2bc";
		$res = Api::refreshISVToken($refreshToken, $userId, $appSecret);
		return $res;
	}
	
	public function applylist(){
	    //根据当前账号查询区域
        $com = (new Common())->pidTokenId();
        $whe=new Where();
        //$whe['community_id'] = array('in',implode(',',$com['community_id']));
        $whe['community_id'] = array('in',$com['community_id']);
        //根据账号查询停车场

        $parkinglist = (new orderService())->parkingList($whe);
        $this->assign('parkinglist',$parkinglist);

        //查询停车场ID
        //var_dump($parkinglist );
        if(!empty($parkinglist)){
            foreach($parkinglist as $park){
                $parkingNo[] = $park['parkingNo'];
            }
            //将数组转换成字符串
            $parkingNo = implode(',',$parkingNo);
        }else{
            $parkingNo = null;
        }
        $where=array();
        $data=request()->get();
        if (!empty($data)){
            if(!empty($data['parkingNo'])){
                $where[]=['parkingNo','=',$data['parkingNo']];
                //$where['parkingNo'] = $data['parkingNo'];//停车场名称
            }
			

            if(!empty($data['car_number'])){
                $where[]=['car_number','like','%'.$data['car_number'].'%'];
                //$where['car_number'] = $data['car_number'];
            }
            $this->assign('where',$where);

        }
		
        $page = request()->has('page') ? request()->get('page') : 1;
        //多条件查询信息

        $list = Db::table("car_order_invoice_apply")->where("parkingNo","in",$parkingNo)->where($where)->order('id desc')->paginate(20, false, [
            'page'  =>  $page,
            'query' =>  $where
        ]);
        $number =Db::table("car_order_invoice_apply")->where("parkingNo","in",$parkingNo)->where($where)->count();
        $this->assign('number',$number);
        $this->assign('list',$list);
        
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }
        return $this->fetch('apply_list');
	}
	
	public function invoiceUpdate(){
		$id=request()->get("id");
		$res=Db::table("car_order_invoice_apply")->where("id",$id)->update(["invoice_state"=>"1"]);
		if($res){
			$this->success("修改成功");
		}else{
			$this->error("修改失败");
		}
	}

	public function invoice(){
	    $id=request()->get("id");
        $applyinfo=Db::table("car_order_invoice_apply")->where("id",$id)->find();
        if(empty($applyinfo)){
            return ;
        }

        $serviceinfo=(new invoiceService())->parkingInvoice($applyinfo["parkingNo"]);

        $money=$applyinfo["money"];
        //税率
        $taxrate=$serviceinfo["taxrate"];
        //税额
        $tax=$taxrate*$money;
        $invoiceDetail= "{'goodsName':'车位费','num':'1','price':'{$money}','withTaxFlag':'1','taxRate':'{$taxrate}','tax':'{$tax}'}";
        $remark=$applyinfo["parkingName"];

        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);

        if($second <86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{

            //过期从新获取
            $res = (new invoiceService())->getToken($serviceinfo['service_id']);

            if(array_key_exists("error",$res)){
                $res["errorCode"]="1";
                $res["error"]= $res["error_description"];

                return json(['error' => $res["error_description"]]);
            }

            $access_token = $res['fp_access_token'];
        }

        $webinfo=Db::table("webset")->where("id","1")->find();
        $appKey = $webinfo["appKey"];
        $appSecret = $webinfo["appSecret"];
        $token = $access_token;// please store the token and refresh it before expired
        $taxnum = $serviceinfo["fp_saler_tax_num"];

        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        $method = "nuonuo.electronInvoice.requestBilling"; // change to your method
        $senid = uniqid(); // generate your meaningful senid

        $invoiceDate = date('Y-m-d H:i:s',time());
        $orderNo = time().rand(100000,999999);
        $timestmp = time();
        $buyerName=$applyinfo["buyerName"];
        if(empty($buyerName)){
            $buyerName="个人";
        }
        $buyerPhone=$applyinfo["phone"];

        $buyerTaxNum=$applyinfo["buyerTaxNum"];
        $buyerTel=$applyinfo["buyerTel"];
        $buyerAddress=$applyinfo["buyerAddress"];
        $buyerAccount=$applyinfo["account"];


        $fp_saler_tax_num=$serviceinfo['fp_saler_tax_num'];
        $salerTel=$serviceinfo['phone'];
        $salerAddress=$serviceinfo['address'];
        $salerAccount=$serviceinfo['fp_saler_account'];

        $body = "{
        \"order\": {
            \"buyerName\": \"$buyerName\",
            \"orderNo\": \"$orderNo\",
            \"buyerTaxNum\": \"$buyerTaxNum\",
            \"buyerTel\": \"$buyerTel\",
            \"buyerAddress\": \"$buyerAddress\",
            \"buyerAccount\": \"$buyerAccount\",
            \"invoiceDate\": \"$invoiceDate\",
            \"clerk\": \"\",
            \"salerTaxNum\": \"$fp_saler_tax_num\",
            \"salerTel\": \"$salerTel\",
            \"salerAddress\": \"$salerAddress\",
            \"salerAccount\": \"$salerAccount\",
            \"invoiceType\": \"1\",
            \"pushMode\": \"1\",
            \"buyerPhone\": \"$buyerPhone\",
            \"remark\": \"$remark\",
            \"invoiceDetail\": [$invoiceDetail],
            \"callBackUrl\": \"/\"
            }
        }";
        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        //var_dump($result);
        $result = json_decode($result, true);
        //Log::write($result,"invoiceresult");
        if($result['code'] == 'E0000'){
            $invoiceSerialNum = $result['result']['invoiceSerialNum'];
            $invoice["invoice_serial_num"] = $result['result']['invoiceSerialNum'];
            $invoice["invoice_time"]=date('Y-m-d H:i:s');
            $invoice["invoice_state"]="1";


            $res=Db::table('car_order_invoice_apply')->where('id', $id)->update($invoice);


            return json(['info' => '开票成功']);
        }else{
            $res["errorCode"]="1";
            $res["error"]= $result['describe'];
            return json(['error' => $result['describe']]);
        }










    }
	public function CheckEInvoice(){
        $id=request()->param("uid");


        $data=Db::table("car_order_invoice_apply")->where("id",$id)->find();
        //echo Db::table("car_order_invoice_apply")->getLastSql();

        if(empty($data)){
            return "账单信息不存在";
        }

        //查询发票序列号


        if(!empty($data["invoiceFileUrl"])){

            return redirect($data["invoiceFileUrl"]);
        }

        //根据商家id查询开票信息
        $serviceinfo=(new invoiceService())->parkingInvoice($data["parkingNo"]);

        //判断access_token是否到期
        $second = strtotime(date('Y-m-d H:i:s',time()))-strtotime($serviceinfo['fp_expires_in']);
        if($second <86400){
            //未过期
            $access_token = $serviceinfo['fp_access_token'];
        }else{
            //过期从新获取
            $res = (new invoiceService())->getToken($serviceinfo['service_id']);
            if(array_key_exists("error",$res)){
                return json(['error' => $res["error_description"]]);

            }
            $access_token = $res['fp_access_token'];
        }
        //var_dump($access_token);die;
        $timestmp = time();

        $webinfo=Db::table("webset")->where("id","1")->find();
        $appKey = $webinfo["appKey"];
        $appSecret = $webinfo["appSecret"];
        $token = $access_token;// please store the token and refresh it before expired
        $taxnum = $serviceinfo["fp_saler_tax_num"];

        $url = "https://sdk.nuonuo.com/open/v1/services"; // change to online domain
        $method = "nuonuo.electronInvoice.CheckEInvoice"; // change to your method
        $senid = uniqid(); // generate your meaningful senid
        $body = json_encode(
            array(
                "invoiceSerialNum" => array($data['invoice_serial_num'])
            )
        );

        $result = Api::sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);


        $result = json_decode($result, true);

        if($result['code'] == 'E0000'){
            //return $result['result'][0]['invoiceFileUrl'];
            $res=Db::table("car_order_invoice_apply")
                ->where('id',$id)
                ->update([
                    "invoiceFileUrl"=>$result['result'][0]['invoiceFileUrl'],
                    "invoiceNum"=>$result['result'][0]["invoiceNum"],
                    "invoiceCode"=>$result['result'][0]['invoiceCode']
                ]);
            //var_dump($data);die;
            return redirect($result['result'][0]['invoiceFileUrl']);

        }else{
            $res["errorCode"]="1";
            $res["error"]= $result['describe'];

            return json(['error' => $result['describe']]);
        }
    }
	
}